//
// Created by zhaoj on 2021/3/17.
//
//链表代码
#include <stdio.h>
#define Maxsize 100
#include <malloc.h>

typedef int ElemType;

typedef struct Node{
    ElemType data;
    struct Node *next;
}LNode,*LinkList;

void ListInitiate(LinkList L){//初始化
    //L = (LinkList*)malloc(sizeof(LNode));
    LinkList p,q;
    p=L;
    for (int i = 0; i < Maxsize; i++) {
        q=(LinkList)malloc(sizeof(LNode));
        q->next=NULL;
        p->next=q;
        p=q;
        p->data = NULL;
    }
}

int ListLength(LinkList L){//返回节点数
    int num=0;
    LinkList p;
    p=L->next;
    while(p->data)
    {
        num++;
        p=p->next;
    }
    return num;
}

int ListInsert(LinkList L, int i, ElemType x){
    //在链表的第i个节点插入数据元素值x
    if (ListLength(L)>=Maxsize){//如果节点数超过最大值
        printf("链表以满无法插入!\n");
        return 0;
    }
    else if (i<0||i>ListLength(L)){//参数不合法
        printf("参数不合法!\n");
        return 0;
    }
    else{
        for (int k = 0; k <= i; k++) {
            L=L->next;
        }
        if (L->data){
            printf("插入失败");
            return 0;
        }else{
            L->data=x;
            return 1;
        }
    }
}
int ListDelete(LinkList L, int i, ElemType *x){
    //删除节点i处的数据元素x
    if(ListLength(L)<=0){
        printf("链表已空，无元素可删除!\n");
        return 0;
    }
    else if(i<0||i>ListLength(L)){
        printf("参数错误!\n");
        return 0;
    }
    else{
        for (int j = 0; j < i; j++) {
            L=L->next;
        }
        *x = L->next->data;
        LinkList * del=L->next;//单独设置一个指针指向被删除结点，以防丢失
        L->next=L->next->next;//更改前一个结点的指针域
        free(del);
        return 1;
    }
}
int ListGet(LinkList L, int i, ElemType *x){
    if (i<0||i>ListLength(L)){
        printf("参数不合法!\n");
        return 0;
    }
    else{
        for (int j = 0; j <= i; j++) {
            L=L->next;
        }
        *x = L->data;
        return 1;
    }
}
int ListSearch(LinkList L, ElemType x){
    if (ListLength(L)==0){
        printf("空链表\n");
        return 0;
    }
    for (int i = 0; i < ListLength(L); i++) {
        if (L->data == x){
            return i;
        } else{
            L=L->next;
        }
    }
    return -1;
}
int main(int argc,char * argv[]){
    LinkList tolist;
    int i,x;
    ListInitiate(tolist);
    printf("hello world!!!!!!!!!\n");
    for (i = 0;  i<20 ; i++) {
        ListInsert(tolist,i,i+1);
    }
    printf("初始链表： ");
    for (i = 0; i <ListLength(tolist); i++) {
        ListGet(tolist,i,&x);
        printf("%d ",x);
    }
    printf("\n删除第5个结点后：");
    ListDelete(tolist,4,&x);
    for (i = 0; i <ListLength(tolist); i++) {
        ListGet(tolist,i,&x);
        printf("%d ",x);
    }
    printf("\n链表的长度：%d",ListLength(tolist));
    printf("\n在链表中搜索9时得到的索引值：%d", ListSearch(tolist, 9));
    printf("\n在链表中搜索11时得到的索引值：%d",ListSearch(tolist, 11));
    return 0;
}